package com.ruoyi.game.service.impl;

import com.ruoyi.game.constant.GameErrorCode;
import com.ruoyi.game.core.GameRoomCore;
import com.ruoyi.game.core.GameRoundCore;
import com.ruoyi.game.core.GameSetCore;
import com.ruoyi.game.domain.GamePlayer;
import com.ruoyi.game.service.GameRoomMemoryManager;
import com.ruoyi.game.service.IGamePlayerService;
import com.ruoyi.game.service.IGameRoomService;
import com.ruoyi.game.service.IGameWebSocketListener;
import com.ruoyi.game.websocket.handler.GameWebSocketHandler;
import com.ruoyi.game.websocket.message.dto.RoomInfoDTO;
import com.ruoyi.game.websocket.message.packet.ReconnectPush;
import com.ruoyi.game.websocket.message.packet.WsPacket;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
@RequiredArgsConstructor
public class GameWebSocketListenerImpl implements IGameWebSocketListener {

    private final GameRoomMemoryManager roomMemory;
    private final IGamePlayerService gamePlayerService;

    @Override
    public List<WsPacket<?>> onPlayerConnectedAndBuildPackets(Long roomId, Long playerId) {
        List<WsPacket<?>> packets = new ArrayList<>();
        try {
            GameRoomCore room = roomMemory.get(roomId);
            if (room == null) {
                log.error("[onPlayerConnected] 房间不存在: {}", roomId);
                return List.of();
            }

            GamePlayer player = gamePlayerService.selectGamePlayerById(playerId);
            if (player == null) {
                log.warn("[onPlayerConnected] 玩家不存在: {}", playerId);
                return List.of();
            }

            // 判断是否为重连（已在房间且有连接）
            boolean isReconnect = GameWebSocketHandler.isPlayerOnlineInRoom(playerId, roomId);

            int seatIndex = room.join(player);
            log.info("[onPlayerConnected] 玩家 {} 自动加入房间 {}，分配座位 {}", playerId, roomId, seatIndex);


            if (room.getCurrentSet() != null) {
                ReconnectPush reconnectPush = room.getCurrentSet().buildReconnectPush(playerId);
                packets.add(new WsPacket<>("RECONNECT", reconnectPush));
            } else {
                RoomInfoDTO roomInfo = room.buildRoomInfo();
                packets.add(new WsPacket<>("ROOM_INFO", roomInfo));
            }

        } catch (Exception e) {
            log.error("[onPlayerConnected] 玩家自动加入失败", e);
        }
        return packets;
    }

    @Override
    public void onPlayerBeforeReconnect(Long playerId, Long currentRoomId, Long newRoomId) {
        if (currentRoomId != null && !currentRoomId.equals(newRoomId)) {
            log.warn("玩家 {} 已在房间 {}，将准备切换到房间 {}", playerId, currentRoomId, newRoomId);
            GameRoomCore oldRoom = roomMemory.get(currentRoomId);
            if (oldRoom != null) {
                oldRoom.kickOutPlayerByPlayerId(playerId, "您已加入其他房间", "被系统移除");
                log.info("玩家 {} 从旧房间 {} 移除", playerId, currentRoomId);
            }
        }
    }

    @Override
    public void onPlayerBeforeDisconnect(Long playerId, Long roomId) {
        GameRoomCore room = roomMemory.get(roomId);
        if (room != null) {
            log.info("[onPlayerBeforeDisconnect] 玩家 {} 正在离开房间 {}", playerId, roomId);
            room.kickOutPlayerByPlayerId(playerId, "您已断开连接", "离开房间");
        }
    }
}
